package com.bqtv.sport.ui.main.fragment

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.ListView
import android.widget.PopupWindow
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.viewbinding.ViewBinding
import com.bqtv.sport.R
import com.bqtv.sport.app.AppActivity
import com.bqtv.sport.app.AppFragment
import com.bqtv.sport.commen.dialog.MessageDialog
import com.bqtv.sport.databinding.FragmentMessageBinding
import com.bqtv.sport.ui.im.SearchFriendActivity
import com.hjq.base.BaseDialog
import com.hjq.permissions.XXPermissions.REQUEST_CODE
import com.tencent.qcloud.tuicore.TUIConstants
import com.tencent.qcloud.tuicore.TUICore
import com.tencent.qcloud.tuicore.util.ScreenUtil
import com.tencent.qcloud.tuikit.timcommon.component.action.PopActionClickListener
import com.tencent.qcloud.tuikit.timcommon.component.action.PopDialogAdapter
import com.tencent.qcloud.tuikit.timcommon.component.action.PopMenuAction
import com.tencent.qcloud.tuikit.timcommon.util.LayoutUtil
import com.tencent.qcloud.tuikit.tuiconversation.bean.ConversationGroupBean
import com.tencent.qcloud.tuikit.tuiconversation.bean.ConversationInfo
import com.tencent.qcloud.tuikit.tuiconversation.classicui.interfaces.OnConversationAdapterListener
import com.tencent.qcloud.tuikit.tuiconversation.classicui.page.TUIConversationFragment
import com.tencent.qcloud.tuikit.tuiconversation.classicui.page.TUIFoldedConversationActivity
import com.tencent.qcloud.tuikit.tuiconversation.classicui.util.TUIConversationUtils
import com.tencent.qcloud.tuikit.tuiconversation.commonutil.ConversationUtils
import com.tencent.qcloud.tuikit.tuiconversation.commonutil.TUIConversationLog
import com.tencent.qcloud.tuikit.tuiconversation.config.classicui.TUIConversationConfigClassic
import com.tencent.qcloud.tuikit.tuiconversation.presenter.ConversationPresenter
import java.util.Collections


class MessageFragment : AppFragment<FragmentMessageBinding, AppActivity<ViewBinding>>() {
    private lateinit var presenter: ConversationPresenter
    private lateinit var mConversationPopList: ListView
    private lateinit var mConversationPopAdapter: PopDialogAdapter
    private lateinit var mConversationPopWindow: PopupWindow
    private val mConversationPopActions: MutableList<PopMenuAction> = ArrayList<PopMenuAction>()

    companion object {
        private val TAG: String = MessageFragment::class.java.getSimpleName()
        private const val INTENT_KEY_TYPE = "type"
        fun newInstance(): MessageFragment {
            val fragment = MessageFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }

        fun newInstance(type: String?): MessageFragment {
            val fragment = MessageFragment()
            val bundle = Bundle()
            bundle.putString(INTENT_KEY_TYPE, type)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun getViewBinding() = FragmentMessageBinding.inflate(layoutInflater)

    override fun initView() {

    }

    override fun initData() {
        presenter = ConversationPresenter()
        presenter.setConversationListener()
        presenter.setShowType(ConversationPresenter.SHOW_TYPE_CONVERSATION_LIST_WITH_FOLD)
        presenter.setConversationGroupType(ConversationGroupBean.CONVERSATION_GROUP_TYPE_DEFAULT)
        binding.conversationLayout.setPresenter(presenter)

        binding.conversationLayout.initDefault()

        binding.conversationLayout.getConversationList()
            .setOnConversationAdapterListener(object : OnConversationAdapterListener {
                override fun onItemClick(
                    view: View?,
                    viewType: Int,
                    conversationInfo: ConversationInfo
                ) {
                    if (conversationInfo.isMarkFold()) {
                        binding.conversationLayout.clearUnreadStatusOfFoldItem()
                        startFoldedConversationActivity()
                    } else {
                        TUIConversationUtils.startChatActivity(conversationInfo)
                    }
                }

                override fun onItemLongClick(view: View, conversationInfo: ConversationInfo) {
                    showItemPopMenu(view, conversationInfo)
                }

                override fun onConversationChanged(dataSource: MutableList<ConversationInfo?>?) {
                    if (dataSource == null) {
                        return
                    }
                    val conversationInfo = dataSource.get(0)
                    if (conversationInfo == null) {
                        return
                    }
                }
            })

        binding.rlSearch.setOnClickListener {
            SearchFriendActivity.start( getAttachActivity()!!)
        }

        binding.tvGoNotice.setOnClickListener {
            // Check if notification permission is granted
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                    // Request notification permission
                    ActivityCompat.requestPermissions(getAttachActivity()!!,
                        arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                        REQUEST_CODE);
                }
            }
        }

        restoreConversationItemBackground()
    }

    override fun onResume() {
        super.onResume()
        presenter.setFocus(true)
        TUIConversationLog.d(TAG, "onResume")
    }

    override fun onPause() {
        super.onPause()
        presenter.setFocus(false)
        TUIConversationLog.d(TAG, "onPause")
    }

    fun restoreConversationItemBackground() {
        if (binding.conversationLayout.getConversationList()
                .getAdapter() != null && binding.conversationLayout.getConversationList()
                .getAdapter()!!
                .isClick()
        ) {
            binding.conversationLayout.getConversationList().getAdapter()?.setClick(false)
            binding.conversationLayout.getConversationList().getAdapter()?.notifyItemChanged(
                binding.conversationLayout.getConversationList().getAdapter()!!.getCurrentPosition()
            )
        }
    }

    private fun getMarkUnreadPopMenuAction(markUnread: Boolean): PopMenuAction {
        val markUnreadAction = PopMenuAction()
        markUnreadAction.setActionClickListener(object : PopActionClickListener {
            override fun onActionClick(index: Int, data: Any?) {
                binding.conversationLayout.markConversationUnread(
                    data as ConversationInfo?,
                    markUnread
                )
            }
        })
        if (markUnread) {
            markUnreadAction.setActionName(getResources().getString(R.string.mark_unread))
        } else {
            markUnreadAction.setActionName(getResources().getString(R.string.mark_read))
        }
        markUnreadAction.setWeight(900)
        return markUnreadAction
    }

    private fun getDeletePopMenuAction(): PopMenuAction {
        val action = PopMenuAction()
        action.setActionClickListener(object : PopActionClickListener {
            override fun onActionClick(index: Int, data: Any?) {
                var msgDialog = MessageDialog.Builder(context!!)
                msgDialog.setTitle(R.string.kind_reminder)
                    .setMessage(R.string.dissolve_group_clear)
                    .setListener(object : MessageDialog.OnListener {
                        override fun onConfirm(dialog: BaseDialog?) {
                            binding.conversationLayout.deleteConversation(data as ConversationInfo?)
                        }
                    })
                msgDialog.show()
            }
        })
        action.setActionName(getResources().getString(R.string.chat_delete))
        action.setWeight(700)
        return action
    }

    private fun showItemPopMenu(view: View, conversationInfo: ConversationInfo) {
        mConversationPopActions.clear()

        val hideAction = PopMenuAction()
        hideAction.setActionName(getResources().getString(R.string.not_display))
        hideAction.setWeight(800)
        hideAction.setActionClickListener(object : PopActionClickListener {
            override fun onActionClick(index: Int, data: Any?) {
                val conversationInfo = data as ConversationInfo
                if (conversationInfo.isMarkFold()) {
                    binding.conversationLayout.hideFoldedItem(true)
                } else {
                    binding.conversationLayout.markConversationHidden(conversationInfo)
                }
            }
        })
        mConversationPopActions.add(hideAction)

        var markUnreadAction: PopMenuAction? = null
        var deleteAction: PopMenuAction? = null

        if (!conversationInfo.isMarkFold()) {
            if (conversationInfo.getUnRead() > 0) {
                markUnreadAction = getMarkUnreadPopMenuAction(false)
            } else {
                if (conversationInfo.isMarkUnread()) {
                    markUnreadAction = getMarkUnreadPopMenuAction(false)
                } else {
                    markUnreadAction = getMarkUnreadPopMenuAction(true)
                }
            }

            deleteAction = getDeletePopMenuAction()
            mConversationPopActions.add(markUnreadAction)
            mConversationPopActions.add(deleteAction)
            mConversationPopActions.addAll(addMoreConversationAction(conversationInfo))
        }

        val itemPop =
            LayoutInflater.from(getActivity()).inflate(R.layout.conversation_pop_menu_layout, null)
        mConversationPopList = itemPop.findViewById<ListView?>(R.id.pop_menu_list)
        mConversationPopList.setOnItemClickListener(object : AdapterView.OnItemClickListener {
            override fun onItemClick(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                val action: PopMenuAction = mConversationPopActions.get(position)!!
                if (action.getActionClickListener() != null) {
                    action.getActionClickListener().onActionClick(position, conversationInfo)
                }
                mConversationPopWindow.dismiss()
                restoreConversationItemBackground()
            }
        })
        val dataSource = TUIConversationConfigClassic.getConversationMenuItemDataSource()
        if (dataSource != null) {
            val excludeList = dataSource.conversationShouldHideItemsInMoreMenu(conversationInfo)
            if (excludeList != null && !excludeList.isEmpty()) {
                if (excludeList.contains(TUIConversationConfigClassic.HIDE)) {
                    mConversationPopActions.remove(hideAction)
                }
                if (excludeList.contains(TUIConversationConfigClassic.DELETE)) {
                    mConversationPopActions.remove(deleteAction)
                }
            }
            val conversationPopMenuItems =
                dataSource.conversationShouldAddNewItemsToMoreMenu(conversationInfo)
            if (conversationPopMenuItems != null && !conversationPopMenuItems.isEmpty()) {
                mConversationPopActions.addAll(conversationPopMenuItems)
            }
        }
        Collections.sort<PopMenuAction?>(
            mConversationPopActions,
            object : Comparator<PopMenuAction> {
                override fun compare(o1: PopMenuAction, o2: PopMenuAction): Int {
                    return o2.getWeight() - o1.getWeight()
                }
            })
        mConversationPopAdapter = PopDialogAdapter()
        mConversationPopList.setAdapter(mConversationPopAdapter)
        mConversationPopAdapter.setDataSource(mConversationPopActions)
        mConversationPopWindow = PopupWindow(
            itemPop,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
        mConversationPopWindow.setBackgroundDrawable(ColorDrawable())
        mConversationPopWindow.setOutsideTouchable(true)
        val width =
            ConversationUtils.getListUnspecifiedWidth(mConversationPopAdapter, mConversationPopList)
        mConversationPopWindow.setWidth(width)
        mConversationPopWindow.setOnDismissListener(object : PopupWindow.OnDismissListener {
            override fun onDismiss() {
                restoreConversationItemBackground()
            }
        })
        var x = view.getWidth() / 2
        if (LayoutUtil.isRTL()) {
            x = -x
        }
        var y = -view.getHeight() / 3
        val popHeight = ScreenUtil.dip2px(45f) * 3
        if (y + popHeight + view.getY() + view.getHeight() > binding.conversationLayout.getBottom()) {
            y = y - popHeight
        }
        mConversationPopWindow.showAsDropDown(view, x, y, Gravity.TOP or Gravity.START)
    }
    private fun startFoldedConversationActivity() {
        val intent = Intent(getActivity(), TUIFoldedConversationActivity::class.java)
        startActivity(intent)
    }

    protected fun addMoreConversationAction(conversationInfo: ConversationInfo): MutableList<PopMenuAction> {
        val settingsList: MutableList<PopMenuAction> = java.util.ArrayList<PopMenuAction>()
        val param: MutableMap<String?, Any?> = HashMap<String?, Any?>()
        param.put(TUIConstants.TUIConversation.CONTEXT, getContext())
        param.put(TUIConstants.TUIConversation.KEY_CONVERSATION_INFO, conversationInfo)
        val extensionList = TUICore.getExtensionList(
            TUIConstants.TUIConversation.Extension.ConversationPopMenu.CLASSIC_EXTENSION_ID,
            param
        )
        for (extensionInfo in extensionList) {
            val text = extensionInfo.getText()
            if (!TextUtils.isEmpty(text)) {
                val action = PopMenuAction()
                action.setActionClickListener(object : PopActionClickListener {
                    override fun onActionClick(index: Int, data: Any?) {
                        val listener = extensionInfo.getExtensionListener()
                        if (listener != null) {
                            listener.onClicked(null)
                        }
                    }
                })
                action.setWeight(extensionInfo.getWeight())
                action.setActionName(text)
                settingsList.add(action)
            }
        }

        return settingsList
    }

    override fun onDestroy() {
        super.onDestroy()
        TUIConversationLog.d(TAG, "onDestroy")
        if (presenter != null) {
            presenter.destroy()
//            presenter = null
        }
    }
}

